package ncov.dao.impl;

import ncov.dao.StaffDao;
import ncov.model.Staff;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository
public class StaffDaoImpl  implements StaffDao {

    @Autowired
    private SessionFactory sessionFactory;


    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }



    @Override
    public Staff queryById(Integer id) {
        Session session = getSession();
        return session.get(Staff.class, id);
    }

    @Override
    public List<Staff> queryAllByLimit(int offset, int limit) {
        Query query = getSession().createQuery("from Staff");
        query.setMaxResults(limit);
        query.setFirstResult(offset);
        List<Staff> list = query.list();

        for (Staff sf : list){
            System.out.println(sf);
        }

        return null;
    }

    @Override
    public List<Staff> queryAll(Staff staff) {
        Session session = getSession();
        Criteria criteria = session.createCriteria(Staff.class);
        return criteria.list();
    }

    @Override
    public int insert(Staff staff) {
        Session session = getSession();
        Serializable save = session.save(staff);
        System.out.println(save);
        return 0;
    }

    @Override
    public int update(Staff staff) {
        Session session = getSession();
        session.update(staff);
        return 0;
    }


    @Override
    public int  deleteById(Integer id) {
        Session session = null;
        try {
            session = getSession();
            session.beginTransaction();
            Staff staff = new Staff();
            staff.setId(id);
            session.delete(staff);
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
            session.getTransaction().rollback();
        }finally {
            session.close();
        }
        return 0;
    }





}